package com.zyz.O_网络编程.TCP.practice;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: vick
 * @Date: 2025/4/15
 * @Description:
 * @version: 1.0
 */
public class Server {
    public static void main(String[] args) {
        int port = 8888;
        String filePath = "C:\\Users\\14338\\Desktop\\工作2.txt";
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("监听端口");
            Socket socket = serverSocket.accept();
            System.out.println("客户端已连接");
            //拆给你就输入流，接收客户端数据
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            //创建输出流，保存文件内容
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(filePath)));

            //接收客户端数据
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                //写入到本地文件
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
            System.out.println("文件接收成功");
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
